using System;
using System.Collections.Generic;
using System.Text;

namespace Soyuz5.Utility
{
    public static class Boolean
    {
        /// <summary>
        /// Parse a string into a boolean value
        /// </summary>
        /// <param name="value">The value to parse</param>
        /// <param name="default">The default value, in case the string is not a valid boolean value</param>
        /// <returns>The parsed value or the default value</returns>
        public static bool Parse(string value, bool defaultValue)
        {
            if (string.IsNullOrEmpty(value))
                return defaultValue;

            switch (value.Trim().ToLower())
            {
                case "1":
                case "1.0":
                case "on":
                case "true":
                case "yes":
                case "t":
                case "y":
                    return true;
                case "0":
                case "off":
                case "false":
                case "no":
                case "f":
                case "n":
                    return false;
                default:
                    return defaultValue;
            }
        }

        /// <summary>
        /// Parse an object into a boolean value
        /// </summary>
        /// <param name="value">The value to parse</param>
        /// <param name="default">The default value, in case the string is not a valid boolean value</param>
        /// <returns>The parsed value or the default value</returns>
        public static bool Parse(object value, bool defaultValue)
        {
            if(value is bool)
                return (bool)value;

            if(value is bool? && ((bool?)value).HasValue)
                return ((bool?)value).Value;

            if(value == null)
                return defaultValue;

            return Parse(value.ToString(), defaultValue);
        }
    }
}